package com.winchain.chainbill.bill.biz.discount.rx;

import com.shell.bee.persistence.transaction.Transaction;
import com.shell.bee.persistence.transaction.TransactionUtil;
import com.shell.framework.rx.OnErrorNotImplementedSubscriber;
import com.winchain.chainbill.basic.context.TimeoutOperation;
import com.winchain.chainbill.basic.invoice.rx.BillInvoiceDfrUploadUpdateSubscriber;
import com.winchain.chainbill.bill.base.po.CbDct;
import com.winchain.chainbill.bill.biz.Bill;
import com.winchain.chainbill.bill.biz.BillTranEvent;
import com.winchain.chainbill.bill.biz.discount.service.BillDctEventService;
import com.winchain.chainbill.bill.biz.send.rx.BatchBillEvent;
import com.winchain.chainbill.bill.biz.send.vo.BatchBillStats;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import rx.Observable;

@Component
public class BillDctRevRejectSubscriber extends OnErrorNotImplementedSubscriber<BatchBillEvent<String, CbDct>> {
	@Autowired
	private BillDctEventService billDctEventService;
	@Autowired
	private BillDctRevRejectPrntSubscriber billDctRevRejectPrntSubscriber;
	@Autowired
	private BillDctRevRejectChdSubscriber billDctRevRejectChdSubscriber;
	@Autowired
	private BillDctRecoverCpnSubscriber billDctRecoverCpnSubscriber;
	@Autowired
	private BillInvoiceDfrUploadUpdateSubscriber billInvoiceDfrUploadUpdateSubscriber;

	public void onApplicationEvent(BatchBillEvent<String, CbDct> t) {
		List<String> records = t.getRecs();
		BatchBillStats<CbDct> stats = t.getStats();

		final Bill<CbDct> source = new Bill();
		for (final String record : records) {
			try {
				TransactionUtil.execute(new Transaction() {
					public void doInTransaction() {
						BillTranEvent<CbDct> event = BillDctRevRejectSubscriber.this.billDctEventService
								.getBillTranEvent(record, false);

						TimeoutOperation timeoutOpt = new TimeoutOperation();
						timeoutOpt.setOptCode("E004");
						timeoutOpt.setRemark("��������������,������������");
						event.setTimeoutOpt(timeoutOpt);

						source.setRec(event.getBill().getRec());
						source.setSource(event.getBill().getSource());
						event.setValue("dfrState", "D");

						Observable<BillTranEvent<CbDct>> observers = Observable.just(event);
						observers.subscribe(BillDctRevRejectSubscriber.this.billDctRecoverCpnSubscriber);
						observers.subscribe(BillDctRevRejectSubscriber.this.billDctRevRejectPrntSubscriber);
						observers.subscribe(BillDctRevRejectSubscriber.this.billDctRevRejectChdSubscriber);
						observers.subscribe(BillDctRevRejectSubscriber.this.billInvoiceDfrUploadUpdateSubscriber);
					}
				}, new int[0]);

				stats.addPassedRecord(source);
			} catch (Exception e) {
				e.printStackTrace();
				stats.addAbnormalRecord(source);
				stats.addAbnormalMsg(e.getMessage());
			}
		}
	}
}
